package com.onpositive.wiki3.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class LocationProperties {
	
	public final static String LOCATION_CONTENTS_FOLDER="location-contents-folder";
	
	public final static String LOCATION_RAW_VALUES="location-raw-values";
	
	public final static String LOCATION_PROPERTIES_STATS="location-properties-stats";
	
	public final static String LOCATION_WIKI_DUMP="location-wiki-dump";
	
	private static final String PROPERTIES_XML_FILE = "D:/WIKI/LocationProperties.xml";
	private static Properties properties=null;
	private static HashMap<String,String> defaults = new HashMap<String, String>();
	static {
		defaults.put(LOCATION_CONTENTS_FOLDER, "C:/work/Content");
		defaults.put(LOCATION_RAW_VALUES, "C:/work/all/content.txt");
		defaults.put(LOCATION_PROPERTIES_STATS, "C:/work/property-stats.xml");
		defaults.put(LOCATION_WIKI_DUMP, "C:/work/XML/enwiki-20131104-pages-articles-multistream.xml");
	}
	
	public static String getProperty(String key){
		if(properties==null)
			initProperties();
		
		String defVal = defaults.get(key);
		if(properties==null) {			
			return defVal;
		}
		
		return properties.getProperty(key, defVal);
	}
	
	public static void saveProperties(){
		if(properties==null)
			return;
		
		File file = new File(PROPERTIES_XML_FILE);
		if(!file.exists()){
			FileOutputStream fos=null;
			try {
				file.createNewFile();
				fos = new FileOutputStream(file);
				properties.storeToXML(fos, null, "UTF-8");
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}			
		}
	}
	
	private static void initProperties() {
		if(properties==null)
			properties=new Properties();
		
		File file = new File(PROPERTIES_XML_FILE);
		if(file.exists()){
			try {
				FileInputStream fis = new FileInputStream(file);
				properties.loadFromXML(fis);
				fis.close();
			} catch (InvalidPropertiesFormatException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
